package boofbridgeimaj.examples;

import boofbridgeimaj.image.feature.util.DetectDescribePointToEngine_F32;
import boofbridgeimaj.image.util.ImajToBoof;
import boofcv.abst.feature.describe.ConvertTupleDesc;
import boofcv.abst.feature.detdesc.DetectDescribePoint;
import boofcv.factory.feature.describe.FactoryConvertTupleDesc;
import boofcv.factory.feature.detdesc.FactoryDetectDescribe;
import boofcv.struct.feature.TupleDesc_F64;
import boofcv.struct.feature.TupleDesc_S8;
import boofcv.struct.image.ImageFloat32;
import com.twelvemonkeys.io.FileUtil;
import org.openimaj.feature.local.list.LocalFeatureList;
import org.openimaj.image.DisplayUtilities;
import org.openimaj.image.FImage;
import org.openimaj.image.ImageUtilities;
import org.openimaj.image.MBFImage;
import org.openimaj.image.feature.local.engine.Engine;
import org.openimaj.image.feature.local.keypoints.Keypoint;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * @author Peter Abeles
 */
public class ExampleBoofSurfInImaj {
	public static void main( String args[] ) throws IOException {
		// Reading the image as a resource so the png can be packaged up and the example still work.
		File f;
		String imagePath = "/sunflowers.png";
		try {
			f = File.createTempFile("image", ".png");
			f.deleteOnExit();
			InputStream imgStream = ExampleBoofSurfInImaj.class.getResourceAsStream(imagePath);
			if(imgStream == null){
				throw new IOException("Image resource does not exist");
			}
			FileUtil.copy(imgStream, new FileOutputStream(f));
		} catch (IOException e) {
			e.printStackTrace();
			return;
		}

		DetectDescribePoint<ImageFloat32,TupleDesc_F64> boofFeature =
				(DetectDescribePoint)FactoryDetectDescribe.surf(0.0021f, 2, -1, 1, 9, 4, 4,true,ImageFloat32.class);
		ConvertTupleDesc<TupleDesc_F64,TupleDesc_S8> converter =
				FactoryConvertTupleDesc.real_F64_S8(boofFeature.getDescriptorLength());
		Engine<Keypoint, FImage> imajFeature = new DetectDescribePointToEngine_F32<TupleDesc_F64>(boofFeature,converter);

		MBFImage mbfImage = ImageUtilities.readMBF(f);

		System.out.println("Detecting Features");

		LocalFeatureList<Keypoint> found = imajFeature.findFeatures(mbfImage.flatten());

		System.out.println("Found Features: "+found.size());


		Float[] red = new Float[]{1f,0f,0f};
		Float[] blue = new Float[]{0f,0f,1f};
		for( Keypoint kp : found ) {
			int x = (int)kp.getLocation().x;
			int y = (int)kp.getLocation().y;
			int r = (int)(kp.scale*3);

			// draw a cross hair to show feature size
			// TODO use a circle instead
			mbfImage.drawLine(x-r,y,x+r,y,2,blue);
			mbfImage.drawLine(x,y-r,x,y+r,2,blue);
			// Red dot to show the center
			mbfImage.drawPoint(kp.getLocation(),red,2);
		}

		DisplayUtilities.displayName(mbfImage, "BoofCV SURF in OpenIMAJ");
	}
}
